package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.mapstruct.EnInfoConvert;
import cn.com.hhrcw.mapstruct.OpDeliveryHistoryConvert;
import cn.com.hhrcw.mapstruct.OpJobConvert;
import cn.com.hhrcw.params.CommonParams;
import cn.com.hhrcw.params.OpDeliveryHistoryParams;
import cn.com.hhrcw.resumeDeliveryConfig.service.IResumeDeliveryConfigService;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.sms.service.ISysSmsTemplateService;
import cn.com.hhrcw.utils.AgeUtil;
import cn.com.hhrcw.utils.EmailUtil;
import cn.com.hhrcw.utils.NewsUtil;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.validator.constraints.ResumeRequired;
import cn.com.hhrcw.vo.EnInfoVO;
import cn.com.hhrcw.vo.OpDeliveryHistoryVO;
import cn.com.hhrcw.vo.OpJobVO;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 职位-投递记录
 *
 * @author jiangdong
 * @since 2020-10-31
 */
@RestController
@Slf4j
@RequestMapping("/personal/v1/opDeliveryHistory")
@Api(tags = "职位-投递记录")
@Validated
public class OpDeliveryHistoryController extends JeecgController<OpDeliveryHistory, IOpDeliveryHistoryService> {

    @Autowired
    private IOpDeliveryHistoryService opDeliveryHistoryService;

    @Autowired
    private OpDeliveryHistoryConvert opDeliveryHistoryConvert;

    @Autowired
    private IOpJobService jobService;

    @Autowired
    private IEnInfoService enInfoService;

    @Autowired
    private NewsUtil newsUtil;

    @Autowired
    private EnInfoConvert enInfoConvert;

    @Autowired
    private OpJobConvert opJobConvert;

    @Autowired
    private ISysSmsTemplateService sysSmsTemplateService;

    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private IOpBatchService opBatchService;

    @Autowired
    private IOpFilterService opFilterService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ICvUserEduInfoService cvUserEduInfoService;

    @Autowired
    private ICvLanguageLevelService cvLanguageLevelService;

    @Autowired
    private ISsSessionService ssSessionService;

    @Autowired
    private IOpShieldingService shieldingService;

    @Autowired
    private ICvResumeService cvResumeService;

    @Autowired
    private ISysBaseAPI sysBaseApi;

    @Autowired
    private IResumeDeliveryConfigService resumeDeliveryConfigService;

    @Autowired
    private ICvUserWorkInfoService workInfoService;

    /**
     * 投递记录列表
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog("职位-投递记录-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    public Result<Page<OpDeliveryHistoryVO>> list(OpDeliveryHistoryParams params, HttpServletRequest request) {
        QueryWrapper<OpDeliveryHistory> queryWrapper = QueryGenerator.initQueryWrapper(opDeliveryHistoryConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        queryWrapper.eq("user_id", sysUser.getId());
        IPage<OpDeliveryHistory> page = opDeliveryHistoryService.page(params.page(), queryWrapper);
        //分页结果转换器

        Function<OpDeliveryHistory, OpDeliveryHistoryVO> fun = opDeliveryHistory -> {
            OpDeliveryHistoryVO e = new OpDeliveryHistoryVO();
            e = opDeliveryHistoryConvert.toVO(opDeliveryHistory);
            String jobId = e.getJobId();
            OpJob job = jobService.getById(jobId);
            String companyId = e.getCompanyId();
            EnInfo enInfo = enInfoService.getById(companyId);
            EnInfoVO enInfoVO = enInfoConvert.toVO(enInfo);
            OpJobVO jobVO = opJobConvert.toVO(job);
            e.setOpJob(jobVO);
            e.setEnInfo(enInfoVO);
            return e;
        };
        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 个人端-删除用户投递记录
     * @param params
     * @return
     */
    @PostMapping("/dropInfoById")
    public Result dropInfoById(@RequestBody CommonParams params) {
        if (params == null || params.getId() == null) {
            return Result.error("参数错误!");
        }
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        OpDeliveryHistory history = opDeliveryHistoryService.getById(params.getId());
        if (history.getDelFlag()) {
            return Result.error("该记录已被删除，请勿重复操作！");
        } else {
            history.setDelFlag(true).setUpdateBy(sysUser.getId()).setUpdateTime(new Date()).setState(7);
            opDeliveryHistoryService.updateById(history);
            return Result.ok();
        }
    }

    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    public Result<OpDeliveryHistoryVO> queryById(String id) {
        OpDeliveryHistory opDeliveryHistory = opDeliveryHistoryService
            .lambdaQuery()
            .eq(OpDeliveryHistory::getId, id)
            .eq(OpDeliveryHistory::getDelFlag, false)
            .one();
        if (opDeliveryHistory == null) {
            throw new JeecgBootException("数据不存在");
        }
        OpDeliveryHistoryVO vo = opDeliveryHistoryConvert.toVO(opDeliveryHistory);
        String jobId = vo.getJobId();
        OpJob job = jobService.getById(jobId);
        String companyId = vo.getCompanyId();
        EnInfo enInfo = enInfoService.getById(companyId);
        EnInfoVO enInfoVO = enInfoConvert.toVO(enInfo);
        OpJobVO jobVO = opJobConvert.toVO(job);
        vo.setOpJob(jobVO);
        vo.setEnInfo(enInfoVO);
        return Result.ok(vo);
    }

    /**
     * 投递职位
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog("职位-投递记录-添加")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> add(@RequestBody @ResumeRequired(message = "请完善简历信息") OpDeliveryHistoryParams params) {

        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        OpDeliveryHistory opDeliveryHistory = opDeliveryHistoryConvert.toEntity(params);
        String jobId = params.getJobId();
        OpJob opJob = jobService.getById(jobId);
        LambdaUpdateWrapper<OpDeliveryHistory> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(OpDeliveryHistory::getJobId, jobId).eq(OpDeliveryHistory::getUserId, sysUser.getId())
            .eq(OpDeliveryHistory::getDelFlag, false);
        List<OpDeliveryHistory> list = opDeliveryHistoryService.list(updateWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            return Result.error("您已投递过该职位，无需再次投递！");
        }

        String resumeId = params.getResumeId();
        CvResume byId = cvResumeService.getById(resumeId);

        // 应客户要求 配置的专场不能投递附件简历 2021年6月23日  朱修轩加
        String bsId = opJob.getBsId();
        Integer bsType = opJob.getBsType();
        if (bsType == 1 && StringUtils.isNotBlank(bsId)) {
            DictModel dictItem = null;
            List<DictModel> dictModels = sysBaseApi.queryDictItemsByCode("disable_file_resume");
            for (DictModel model : dictModels) {
                if (model.getValue().equals(bsId)) {
                    dictItem = model;
                    break;
                }
            }
            if (null != dictItem) {
                if (byId.getType() == 1) {
                    return Result.error("该专场不支持投递附件简历");
                }
            }

        }
        //jiangdong add
        List<OpShielding> shieldingList = shieldingService.lambdaQuery().eq(OpShielding::getUserId, sysUser.getId()).eq(OpShielding::getComId, opJob.getCompanyId())
            .eq(OpShielding::getDelFlag, false).list();
        if (CollectionUtils.isNotEmpty(shieldingList)) {
            List<String> comIds = shieldingList.stream().map(e -> e.getComId()).collect(Collectors.toList());
            if (comIds.contains(opJob.getCompanyId())) {
                return Result.error("您已屏蔽该公司，暂不能投递！");
            }
        }
        if (0 == opJob.getBsType()) {
            OpBatch batch = opBatchService.getById(opJob.getBsId());
            if (null != batch) {
                Boolean repeatFlag = batch.getRepeatFlag();
                if (!repeatFlag && repeatFlag != null) {
                    List<OpJob> jobList = jobService.lambdaQuery().eq(OpJob::getBsId, batch.getId())
                        .eq(OpJob::getDelFlag, false).list();
                    if (CollUtil.isNotEmpty(jobList)) {
                        List<String> collect = jobList.stream().map(OpJob::getId).collect(Collectors.toList());
                        List<OpDeliveryHistory> history = opDeliveryHistoryService.lambdaQuery().eq(OpDeliveryHistory::getUserId, sysUser.getId())
                            .eq(OpDeliveryHistory::getDelFlag, false).in(OpDeliveryHistory::getJobId, collect).list();
                        if (CollUtil.isNotEmpty(history)) {
                            return Result.error("您已经投递过该公司同批次的其他职位！");
                        }

                    }
                }
            }
        } else if (1 == opJob.getBsType()) {
            SsSession session = ssSessionService.getById(opJob.getBsId());
            Assert.notNull(session, "数据异常！");
            Date startTime = session.getStartTime();
            Date endTime = session.getEndTime();
            if (startTime.after(DateUtil.date())) {
                return Result.error("该专场职位还没开始，暂不能投递！");
            }
            if (endTime.before(DateUtil.date())) {
                return Result.error("该专场职位已结束，暂不能投递！");
            }
            //验证职位是否可以投递
            try {
                resumeDeliveryConfigService.verifyPosition(session.getId(), sysUser.getId(), params.getResumeId());
            } catch (Exception e) {
                return Result.error(e.getMessage());
            }
            Boolean repeatFlag = session.getRepeatFlag();
            if (!repeatFlag && repeatFlag != null) {
                List<OpJob> jobList = jobService.lambdaQuery().eq(OpJob::getBsId, session.getId())
                    .eq(OpJob::getDelFlag, false).list();
                if (CollUtil.isNotEmpty(jobList)) {
                    List<String> collect = jobList.stream().map(OpJob::getId).collect(Collectors.toList());
                    List<OpDeliveryHistory> history = opDeliveryHistoryService.lambdaQuery().eq(OpDeliveryHistory::getUserId, sysUser.getId())
                        .eq(OpDeliveryHistory::getDelFlag, false).in(OpDeliveryHistory::getJobId, collect).list();
                    if (CollUtil.isNotEmpty(history)) {
                        return Result.error("您已经投递过该公司专场的其他职位，暂不能投递！");
                    }

                }
            }

        }
        Boolean flag = true;
        Boolean flag1 = true;
        Boolean flag2 = true;
        Boolean flag3 = true;
        boolean subjectFlag = true;
        PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, sysUser.getId()).eq(PiInfo::getDelFlag, false).one();
        if(StringUtils.isBlank(piInfo.getPhotoId()) || "defaultPic".equals(piInfo.getPhotoId())){
            return Result.error("未上传头像，请上传后再投递。");
        }

        List<CvUserEduInfo> eduInfos = cvUserEduInfoService.lambdaQuery().eq(CvUserEduInfo::getUserId, sysUser.getId())
                .eq(CvUserEduInfo::getDelFlag, false).list();
        // 2023-03-04 加入岗位学历的判断
        //if(null!=opJob.getEduLevel()){
        //    AtomicBoolean mark = new AtomicBoolean(false);
        //    eduInfos.forEach(edu->{
        //        if(edu.getEduLevel()>=opJob.getEduLevel()){
        //            mark.set(true);
        //        }
        //    });
        //    if(!mark.get()){
        //        return Result.error("投递失败！简历不符合本岗位的学历要求");
        //    }
        //}

        if (opJob.getFilterFlag()) {
            String id = opJob.getFilterId();
            OpFilter filter = opFilterService.getById(id);
            if (null != filter) {
//                PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, sysUser.getId()).eq(PiInfo::getDelFlag, false).one();
                Integer maxAge = filter.getJobMaxAge();
                Integer minAge = filter.getJobMinAge();
                Integer jobMaxAge = filter.getMaxExperience();
                Integer jobMinAge = filter.getMinExperience();
                Date birthday = piInfo.getBirthday();
                Date jobTime = piInfo.getJobTime();

                int age = AgeUtil.getAge(birthday);
                if (null != jobMinAge && null != jobMaxAge && null != jobTime) {
                    int jobYear = AgeUtil.getAge(jobTime);
                    if (jobYear < jobMinAge || jobYear > jobMaxAge) {
                        flag = false;
                    }
                }
                if (null != minAge && null != maxAge) {
                    if (age < minAge || age > maxAge) {
                        flag1 = false;
                    }
                }
                if (null != filter.getSex()) {
                    if (piInfo.getSex().equals(filter.getSex())) {
                        flag2 = false;
                    }
                }
                if (StrUtil.isNotBlank(filter.getLanguage())) {
                    List<CvLanguageLevel> languageLevelList = cvLanguageLevelService.lambdaQuery().eq(CvLanguageLevel::getUserId, sysUser.getId())
                        .eq(CvLanguageLevel::getDelFlag, false).list();
                    if (CollUtil.isNotEmpty(languageLevelList)) {
                        String language = "";
                        for (CvLanguageLevel level : languageLevelList) {
                            language += level.getOralLanguageLevel();
                        }
                        if (!language.contains(filter.getLanguage())) {
                            flag3 = false;
                        }
                    } else {
                        flag3 = false;
                    }
                }

                if (StrUtil.isNotBlank(filter.getJobSubject()) || null != filter.getEduLevel()) {
                    if (CollUtil.isNotEmpty(eduInfos)) {
                        String subject = "";
                        Integer edu = 0;
                        for (CvUserEduInfo info : eduInfos) {
                            String major = info.getMajor();
                            Integer level = info.getEduLevel();
                            if (level > edu) {
                                edu = level;
                            }
                            subject += major;
                        }
                        if (edu < filter.getEduLevel()) {
                            flag3 = false;
                        }

                        String jobSubject = filter.getJobSubject();
                        if (StrUtil.isNotBlank(jobSubject)) {
                            subjectFlag = false;
                            String[] split = jobSubject.split(",");

                            for (String s : split) {
                                try {
                                    String query = jdbcTemplate.queryForObject("select item_text from sys_dict_item where item_value = ? ", new Object[]{s}, String.class);
                                    if (StrUtil.isNotBlank(query)) {
                                        if (subject.contains(query)) {
                                            subjectFlag = true;
                                            break;
                                        }
                                    }
                                } catch (Exception e) {
                                    for (StackTraceElement elements : e.getStackTrace()) {
                                        log.error(elements.toString());
                                    }
                                    return Result.error("筛选失败");
                                }
                            }
                        }
                    }
                }

                if (flag && flag1 && flag2 && subjectFlag && flag3) {
                    opDeliveryHistory.setScreenFlag(true);
                    opDeliveryHistory.setState(0);
                } else {
                    opDeliveryHistory.setState(7);
                    opDeliveryHistory.setScreenFlag(false);
                }

            } else {
                opDeliveryHistory.setScreenFlag(true);
                opDeliveryHistory.setState(0);
            }

        } else {
            opDeliveryHistory.setScreenFlag(true);
            opDeliveryHistory.setState(0);
        }

        // 增加工作经历空白期校验
        if(!checkWorkExperience(resumeId,byId)){
            return Result.error("工作经历之间如超过3个月的空白期 或 存在多个至今的工作经历，请在“其他事项”中补充相关说明后再投递。");
        }

        opDeliveryHistory.setCreateBy(sysUser.getId());
        opDeliveryHistory.setCreateTime(DateUtil.date());
        opDeliveryHistory.setDelFlag(false);
        opDeliveryHistory.setCompanyId(opJob.getCompanyId());
        String uuid = UuidUtils.getUUID().substring(0, 32);
        opDeliveryHistory.setId(uuid);
        opDeliveryHistory.setUserId(sysUser.getId());
        boolean saved = opDeliveryHistoryService.save(opDeliveryHistory);
        if (saved) {
            if (null != opJob && opDeliveryHistory.getState() == 0) {

                newsUtil.creatNews(opJob.getCreateBy(), sysUser.getId(), 1, 0, uuid, "0");
                Map<String, String> map = emailUtil.creatEmail(opJob.getCreateBy(), sysUser.getId(), 1, 0, uuid, "0");
                piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, opJob.getCreateBy()).eq(PiInfo::getDelFlag, false).one();
                if (null != piInfo) {
                    String[] mobile1 = new String[]{piInfo.getPhone()};
                    sysSmsTemplateService.sendSms(mobile1, map.get("content"));
                }
                Integer deliveryCount = opJob.getDeliveryCount();
                opJob.setDeliveryCount((deliveryCount == null || deliveryCount == 0) ? 1 : deliveryCount + 1);
                jobService.updateById(opJob);
            }
        }
        return saved ? Result.ok() : Result.error("投递失败");
    }

    /**
     * 投递职位   移动端使用
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/newadd")
    @AutoLog("职位-投递记录-添加")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> newadd(@RequestBody @ResumeRequired(message = "请完善简历信息") OpDeliveryHistoryParams params) {

        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        OpDeliveryHistory opDeliveryHistory = opDeliveryHistoryConvert.toEntity(params);
        String jobId = params.getJobId();
        OpJob opJob = jobService.getById(jobId);
        LambdaUpdateWrapper<OpDeliveryHistory> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(OpDeliveryHistory::getJobId, jobId).eq(OpDeliveryHistory::getUserId, sysUser.getId())
                .eq(OpDeliveryHistory::getDelFlag, false);
        List<OpDeliveryHistory> list = opDeliveryHistoryService.list(updateWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            return Result.error("您已投递过该职位，无需再次投递！");
        }

        String resumeId = params.getResumeId();
        CvResume byId = cvResumeService.getById(resumeId);

        // 应客户要求 配置的专场不能投递附件简历 2021年6月23日  朱修轩加
        String bsId = opJob.getBsId();
        Integer bsType = opJob.getBsType();
        if (bsType == 1 && StringUtils.isNotBlank(bsId)) {
            DictModel dictItem = null;
            List<DictModel> dictModels = sysBaseApi.queryDictItemsByCode("disable_file_resume");
            for (DictModel model : dictModels) {
                if (model.getValue().equals(bsId)) {
                    dictItem = model;
                    break;
                }
            }
            if (null != dictItem) {
                if (byId.getType() == 1) {
                    return Result.error("该专场不支持投递附件简历");
                }
            }

        }
        //jiangdong add
        List<OpShielding> shieldingList = shieldingService.lambdaQuery().eq(OpShielding::getUserId, sysUser.getId()).eq(OpShielding::getComId, opJob.getCompanyId())
                .eq(OpShielding::getDelFlag, false).list();
        if (CollectionUtils.isNotEmpty(shieldingList)) {
            List<String> comIds = shieldingList.stream().map(e -> e.getComId()).collect(Collectors.toList());
            if (comIds.contains(opJob.getCompanyId())) {
                return Result.error("您已屏蔽该公司，暂不能投递！");
            }
        }
        if (0 == opJob.getBsType()) {
            OpBatch batch = opBatchService.getById(opJob.getBsId());
            if (null != batch) {
                Boolean repeatFlag = batch.getRepeatFlag();
                if (!repeatFlag && repeatFlag != null) {
                    List<OpJob> jobList = jobService.lambdaQuery().eq(OpJob::getBsId, batch.getId())
                            .eq(OpJob::getDelFlag, false).list();
                    if (CollUtil.isNotEmpty(jobList)) {
                        List<String> collect = jobList.stream().map(OpJob::getId).collect(Collectors.toList());
                        List<OpDeliveryHistory> history = opDeliveryHistoryService.lambdaQuery().eq(OpDeliveryHistory::getUserId, sysUser.getId())
                                .eq(OpDeliveryHistory::getDelFlag, false).in(OpDeliveryHistory::getJobId, collect).list();
                        if (CollUtil.isNotEmpty(history)) {
                            return Result.error("您已经投递过该公司同批次的其他职位！");
                        }

                    }
                }
            }
        } else if (1 == opJob.getBsType()) {
            SsSession session = ssSessionService.getById(opJob.getBsId());
            Assert.notNull(session, "数据异常！");
            Date startTime = session.getStartTime();
            Date endTime = session.getEndTime();
            if (startTime.after(DateUtil.date())) {
                return Result.error("该专场职位还没开始，暂不能投递！");
            }
            if (endTime.before(DateUtil.date())) {
                return Result.error("该专场职位已结束，暂不能投递！");
            }
            Boolean repeatFlag = session.getRepeatFlag();
            if (!repeatFlag && repeatFlag != null) {
                List<OpJob> jobList = jobService.lambdaQuery().eq(OpJob::getBsId, session.getId())
                        .eq(OpJob::getDelFlag, false).list();
                if (CollUtil.isNotEmpty(jobList)) {
                    List<String> collect = jobList.stream().map(OpJob::getId).collect(Collectors.toList());
                    List<OpDeliveryHistory> history = opDeliveryHistoryService.lambdaQuery().eq(OpDeliveryHistory::getUserId, sysUser.getId())
                            .eq(OpDeliveryHistory::getDelFlag, false).in(OpDeliveryHistory::getJobId, collect).list();
                    if (CollUtil.isNotEmpty(history)) {
                        return Result.error("您已经投递过该公司专场的其他职位，暂不能投递！");
                    }

                }
            }

        }
        Boolean flag = true;
        Boolean flag1 = true;
        Boolean flag2 = true;
        Boolean flag3 = true;
        boolean subjectFlag = true;
        PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, sysUser.getId()).eq(PiInfo::getDelFlag, false).one();
        List<CvUserEduInfo> eduInfos = cvUserEduInfoService.lambdaQuery().eq(CvUserEduInfo::getUserId, sysUser.getId())
                .eq(CvUserEduInfo::getDelFlag, false).list();

        if (opJob.getFilterFlag()) {
            String id = opJob.getFilterId();
            OpFilter filter = opFilterService.getById(id);
            if (null != filter) {
                Integer maxAge = filter.getJobMaxAge();
                Integer minAge = filter.getJobMinAge();
                Integer jobMaxAge = filter.getMaxExperience();
                Integer jobMinAge = filter.getMinExperience();
                Date birthday = piInfo.getBirthday();
                Date jobTime = piInfo.getJobTime();

                int age = AgeUtil.getAge(birthday);
                if (null != jobMinAge && null != jobMaxAge && null != jobTime) {
                    int jobYear = AgeUtil.getAge(jobTime);
                    if (jobYear < jobMinAge || jobYear > jobMaxAge) {
                        flag = false;
                    }
                }
                if (null != minAge && null != maxAge) {
                    if (age < minAge || age > maxAge) {
                        flag1 = false;
                    }
                }
                if (null != filter.getSex()) {
                    if (piInfo.getSex().equals(filter.getSex())) {
                        flag2 = false;
                    }
                }
                if (StrUtil.isNotBlank(filter.getLanguage())) {
                    List<CvLanguageLevel> languageLevelList = cvLanguageLevelService.lambdaQuery().eq(CvLanguageLevel::getUserId, sysUser.getId())
                            .eq(CvLanguageLevel::getDelFlag, false).list();
                    if (CollUtil.isNotEmpty(languageLevelList)) {
                        String language = "";
                        for (CvLanguageLevel level : languageLevelList) {
                            language += level.getOralLanguageLevel();
                        }
                        if (!language.contains(filter.getLanguage())) {
                            flag3 = false;
                        }
                    } else {
                        flag3 = false;
                    }
                }

                if (StrUtil.isNotBlank(filter.getJobSubject()) || null != filter.getEduLevel()) {
                    if (CollUtil.isNotEmpty(eduInfos)) {
                        String subject = "";
                        Integer edu = 0;
                        for (CvUserEduInfo info : eduInfos) {
                            String major = info.getMajor();
                            Integer level = info.getEduLevel();
                            if (level > edu) {
                                edu = level;
                            }
                            subject += major;
                        }
                        if (edu < filter.getEduLevel()) {
                            flag3 = false;
                        }

                        String jobSubject = filter.getJobSubject();
                        if (StrUtil.isNotBlank(jobSubject)) {
                            subjectFlag = false;
                            String[] split = jobSubject.split(",");

                            for (String s : split) {
                                try {
                                    String query = jdbcTemplate.queryForObject("select item_text from sys_dict_item where item_value = ? ", new Object[]{s}, String.class);
                                    if (StrUtil.isNotBlank(query)) {
                                        if (subject.contains(query)) {
                                            subjectFlag = true;
                                            break;
                                        }
                                    }
                                } catch (Exception e) {
                                    for (StackTraceElement elements : e.getStackTrace()) {
                                        log.error(elements.toString());
                                    }
                                    return Result.error("筛选失败");
                                }
                            }
                        }
                    }
                }

                if (flag && flag1 && flag2 && subjectFlag && flag3) {
                    opDeliveryHistory.setScreenFlag(true);
                    opDeliveryHistory.setState(0);
                } else {
                    opDeliveryHistory.setState(7);
                    opDeliveryHistory.setScreenFlag(false);
                }

            } else {
                opDeliveryHistory.setScreenFlag(true);
                opDeliveryHistory.setState(0);
            }

        } else {
            opDeliveryHistory.setScreenFlag(true);
            opDeliveryHistory.setState(0);
        }

        opDeliveryHistory.setCreateBy(sysUser.getId());
        opDeliveryHistory.setCreateTime(DateUtil.date());
        opDeliveryHistory.setDelFlag(false);
        opDeliveryHistory.setCompanyId(opJob.getCompanyId());
        String uuid = UuidUtils.getUUID().substring(0, 32);
        opDeliveryHistory.setId(uuid);
        opDeliveryHistory.setUserId(sysUser.getId());
        boolean saved = opDeliveryHistoryService.save(opDeliveryHistory);
        if (saved) {
            if (null != opJob && opDeliveryHistory.getState() == 0) {

                newsUtil.creatNews(opJob.getCreateBy(), sysUser.getId(), 1, 0, uuid, "0");
                Map<String, String> map = emailUtil.creatEmail(opJob.getCreateBy(), sysUser.getId(), 1, 0, uuid, "0");
                piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, opJob.getCreateBy()).eq(PiInfo::getDelFlag, false).one();
                if (null != piInfo) {
                    String[] mobile1 = new String[]{piInfo.getPhone()};
                    sysSmsTemplateService.sendSms(mobile1, map.get("content"));
                }
                Integer deliveryCount = opJob.getDeliveryCount();
                opJob.setDeliveryCount((deliveryCount == null || deliveryCount == 0) ? 1 : deliveryCount + 1);
                jobService.updateById(opJob);
            }
        }
        return saved ? Result.ok() : Result.error("投递失败");
    }


    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog("职位-投递记录-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("opDeliveryHistory:edit")
    public Result<?> edit(@RequestBody @Valid OpDeliveryHistoryParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        OpDeliveryHistory opDeliveryHistory = opDeliveryHistoryConvert.toEntity(params);
        opDeliveryHistory.setUpdateBy(sysUser.getId());
        opDeliveryHistory.setUpdateTime(DateUtil.date());

        boolean updated = opDeliveryHistoryService.updateById(opDeliveryHistory);
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog("职位-投递记录-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("opDeliveryHistory:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<OpDeliveryHistory> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(OpDeliveryHistory::getId, id)
            .set(OpDeliveryHistory::getDelFlag, true)
            .set(OpDeliveryHistory::getUpdateBy, sysUser.getUsername())
            .set(OpDeliveryHistory::getUpdateTime, DateUtil.date());

        boolean deleted = opDeliveryHistoryService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, OpDeliveryHistoryParams params) {
        OpDeliveryHistory opDeliveryHistory = opDeliveryHistoryConvert.toEntity(params);
        opDeliveryHistory.setDelFlag(false);
        QueryWrapper<OpDeliveryHistory> queryWrapper = QueryGenerator.initQueryWrapper(opDeliveryHistory, request.getParameterMap());
        List<OpDeliveryHistory> data = opDeliveryHistoryService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("职位-投递记录", "职位-投递记录");
        String url = super.exportXls(exportParams, OpDeliveryHistoryVO.class, opDeliveryHistoryConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OpDeliveryHistory.class);
    }

    /**
     * 获取简历对应的工作经历，校验工作经历空白期是否超 90 天
     * @param resumeId
     * @return
     */
    private boolean checkWorkExperience(String resumeId,CvResume resume) {
        LambdaQueryWrapper<CvUserWorkInfo> workInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        workInfoLambdaQueryWrapper.eq(CvUserWorkInfo::getDelFlag, false).eq(CvUserWorkInfo::getResumeId, resumeId).orderByDesc(CvUserWorkInfo::getWorkStartTime);
        //工作经历
        List<CvUserWorkInfo> workInfos = workInfoService.list(workInfoLambdaQueryWrapper);
        if(workInfos.isEmpty()){
            return true;
        }
        for (int i = 0; i < workInfos.size(); i++) {
            if(workInfos.get(i).getWorkStartTime()!=null && StringUtils.isNotBlank(workInfos.get(i).getWorkEndTime())){
                if(i==0){ //最近的工作经历
                    String endWorkTime = workInfos.get(i).getWorkEndTime();
                    if(!endWorkTime.equals(CommonConstant.TO_THIS_DAY)){
                        Date endTime = DateUtils.str2Date(endWorkTime, DateUtils.date_sdf.get());
                        if(DateUtils.check(endTime,new Date()) && StringUtils.isBlank(resume.getOtherSituations())){
                            log.info("resumeId:"+resumeId+" 工作经历时间超过90天的空白期，请在“其他事项”中补充相关说明。");
                            return false;
                        }
                    }
                }else { // 之前的工作经历，比较上段工作经历的结束时间和下段工作经历的开始时间
                    String startTime = workInfos.get(i).getWorkEndTime();
                    Date endTime = workInfos.get(i-1).getWorkStartTime();
                    if(startTime.equals(CommonConstant.TO_THIS_DAY)  &&
                            (StringUtils.isBlank(resume.getOtherSituations()) || resume.getOtherSituations().trim().equals("无"))){
                        log.info("resumeId:"+resumeId+" 工作经历【" + startTime + "】存在不合规选项，请检查。");
                        return false;
                    } else if (!startTime.equals(CommonConstant.TO_THIS_DAY)  && DateUtils.check(DateUtils.str2Date(startTime, DateUtils.date_sdf.get()), endTime)
                                   && StringUtils.isBlank(resume.getOtherSituations())) {
                        log.info("resumeId:"+resumeId+" 工作经历时间超过90天的空白期，请在“其他事项”中补充相关说明。");
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
